<script setup>
import { onMounted, ref } from 'vue';
import {useRouter, useRoute} from 'vue-router';
import { useAuthStore, setFromLocalStorage } from '@/stores/auth.js';
import ButtonGroup from '@/components/ButtonGroup.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { queryAllUserByPageAPI, editUserInfo, deleteUserAPI } from '@/apis/user.js';

const router = useRouter();
const authStore = useAuthStore();
const buttonList = [
  {
    key: 'users',
    text: '全部用户',
    icon: {
      active: '/icon/users-blue.png',
      normal: '/icon/users-black.png'
    }
  },
  {
    key: 'admin',
    text: '管理员用户',
    icon: {
      active: '/icon/admin-blue.png',
      normal: '/icon/admin-black.png'
    }
  },
  {
    key: 'user',
    text: '普通用户',
    icon: {
      active: '/icon/user-blue.png',
      normal: '/icon/user-black.png'
    }
  },
];
const selectedBtn = ref('users');

const handlerSelectBtn = (key) => {
  selectedBtn.value = key;
  queryUsers();
}

// 输入框
const input = ref();

/* ------表格------- */
const tableData = ref([]);

const handleOperate = (row) => {
  console.log(row);
}


/* ------分页条------- */
const total = ref(0); // 总数据条数
const currentPage = ref(1); // 当前页码
const pageSize = ref(7); // 每页显示条数

// 每页条数变化时的回调
const handleSizeChange = (val) => {
  pageSize.value = val;
  queryUsers();
};

// 当前页码变化时的回调
const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryUsers();
};

// 点击搜索图标触发查询
const handleSearch = () => {
  queryUsers();
};
// 清除搜索框内容后触发查询
const handleClearInput = () => {
  queryUsers();      
};

// 构造请求参数（根据按钮、搜索框、分页状态）
const getQueryParams = () => {
  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    username: input.value?.trim() || '' // 用户名称
  };

  // 根据选中的按钮，添加对应的筛选条件
  switch (selectedBtn.value) {
    case 'users': // 全部用户
      break;
    case 'admin': // 管理员
      params.role = 'ADMIN';
      break;
    case 'user': // 普通用户
      params.role = 'USER'; 
      break;
    default:
      break;
  }
  return params;
};

const queryUsers = async () => {
  const params = getQueryParams();
  const res = await queryAllUserByPageAPI(params);
  console.log(res);
  tableData.value = res.data.records;
  total.value = res.data.total;
}

// 对话框
const dialogVisible  = ref(false);
const selectedUser = ref({});
const userRoleList = ['ADMIN', 'USER'];
const userStatusList = ['ACTIVE', 'INACTIVE'];
// 打开对话框
const openDialog = (row) => {
  dialogVisible.value = true;
  selectedUser.value = {...row};
};

// 关闭对话框并重置表单
const closeDialog = () => {
  dialogVisible.value = false;
  selectedUser.value = {};  
};

// 修改用户角色/状态
const submitDialog = async () => {
  const res = await editUserInfo(selectedUser.value);
  if(res.code === 1) {
    ElMessage.success('修改成功');

    const isModifySelf = selectedUser.value.username === authStore.username;
    console.log(isModifySelf);
    if (isModifySelf) {
      const oldRole = authStore.role; 
      const newRole = selectedUser.value.role;
      
      // 再更新 Pinia 和 localStorage 的角色
      authStore.role = newRole;
      setFromLocalStorage('role', newRole);
      
      // 重新拉取用户详情，确保 userDetail 与后端一致
      await authStore.getUserDetail();
      
      // 处理角色变更后的路由适配 
      // 管理员 → 普通用户
      if (oldRole === 'ADMIN' && newRole === 'USER' && router.currentRoute.value.path.startsWith('/back')) {
        ElMessage.warning('你的权限已变更，将退出管理后台');
        router.push('/'); // 跳转到前台首页
      }
    }
    closeDialog();
    queryUsers();
  }else {
    ElMessage.error('修改失败，请检查网络设置');
  }
  
}

const deleteUser = async (row) => {
  // 弹出确认弹窗
  await ElMessageBox.confirm(
      '确定要删除这个用户吗？【无法恢复】',
      '删除申请',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning' 
      }
  );
  await deleteUserAPI(row.userId);
  ElMessage.success('删除成功');
  queryUsers();
}

onMounted(() => {
  queryUsers();
})
</script>
<template>
        <div class="bar">
            <!-- 按钮组 -->
            <ButtonGroup
              :buttonList="buttonList"
              :selectedBtn="selectedBtn"
              @select="handlerSelectBtn"
            />
             <div class="search-input">
              <el-input
                v-model="input"
                @keyup.enter="handleSearch"
                @clear="handleClearInput"
                style="width: 452px; height: 42px;"
                placeholder="搜索用户名称"
                clearable
              >
                <template #prefix>
                  <img src="/icon/search.png" alt="搜索图标" width="18px" height="18px" @click="handleSearch" style="cursor: pointer;">
                </template>
              </el-input>
             </div>

    </div>

    <div class="table">
            <el-table 
              :data="tableData" 
              style="width: 100%;"
              row-height="60px" 
              max-height="598px"
              :header-cell-style="{
                background: '#FAFAFA',
                color: '#404040',
                fontWeight: 'bold',
                height: '66px'
              }"
            >
            <!-- 名字 -->
              <el-table-column prop="username" align="center">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/user-black.png" alt="" width="18px" height="18px">
                    <span>名字</span>
                  </div>
                </template>
              </el-table-column>

              <!-- 邮箱 -->
              <el-table-column prop="email" align="center">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/email.png" alt="" width="18px" height="18px">
                    <span>邮箱</span>
                  </div>
                </template>
              </el-table-column>
              
              <!-- 手机号 -->
              <el-table-column align="center" width="250">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/phone-black.png" alt="" width="18px" height="18px">
                    <span>手机号</span>
                  </div>
                </template>
                <template #default="scope">
                  {{ scope.row.phone ? scope.row.phone : '暂未填写' }}
                </template>
              </el-table-column>
              
              <!-- 身份 -->
              <el-table-column prop="role" align="center" width="250">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/id-card-black.png" alt="" width="18px" height="18px">
                    <span>身份</span>
                  </div>
                </template>
                <template #default="scope">
                  <div 
                    class="status"
                    :style="{backgroundColor: scope.row.role === 'ADMIN' ? '#FF6448' : '#2BAFF5'}"
                  >
                    <span>{{ scope.row.role }}</span>
                    
                  </div>
                </template>
              </el-table-column>

              <!-- 状态 -->
              <el-table-column prop="status" align="center" width="250">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/status.png" alt="" width="18px" height="18px">
                    <span>状态</span>
                  </div>
                </template>
                <template #default="scope">
                  <div 
                    class="status"
                    :style="{backgroundColor: scope.row.status === 'ACTIVE' ? '#31C84B' : '#FFAD09'}"
                  >
                    <span>{{ scope.row.status }}</span>
                    
                  </div>
                </template>
              </el-table-column>
              
              <!-- 操作 -->
              <el-table-column align="center">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/operate.png" alt="" width="18px" height="18px">
                    <span>操作</span>
                  </div>
                </template>
                <template #default="scope">
                  <div>
                    <el-button 
                      type="text" 
                      @click="openDialog(scope.row)"
                    >
                      <img 
                        src="/icon/write-black.png"
                        alt="操作" 
                        width="28px" 
                        height="28px"
                      >
                    </el-button>
                    <el-button 
                      type="text" 
                      @click="deleteUser(scope.row)"
                    >
                      <img 
                        src="/icon/delete.png"
                        alt="操作" 
                        width="28px" 
                        height="28px"
                      >
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页条 -->
             <div class="pagination">
                <el-pagination
                  v-model:current-page="currentPage"  
                  v-model:page-size="pageSize"        
                  :total="total"                     
                  layout="total, prev, pager, next, jumper, slot" 
                  @size-change="handleSizeChange"    
                  @current-change="handleCurrentChange"  
                >
                </el-pagination>
             </div>
    </div>

    <!-- 修改用户权限对话框 -->
         <!-- 遮罩层 -->
         <div 
            class="dialog-mask" 
            v-show="dialogVisible" 
        >
            <!-- 对话框内容 -->
            <div class="dialog-content">
                <!-- 对话框头部 -->
                <div class="dialog-header">
                    <span class="dialog-title">编辑用户权限</span>
                    <button class="close-btn" @click="closeDialog">
                        <img src="/icon/x.png" alt="关闭图标" width="20px" height="20px">
                    </button>
                </div>
                <!-- 对话框主体 -->
                <div class="dialog-body">
                    <!-- 用户信息 -->
                    <div class="input-box">
                        <div class="input-label">
                            <span>姓名</span>
                        </div>
                        <div class="input-container">
                            <span class="input-inner">{{ selectedUser.username }}</span>
                        </div>
                    </div>
                    <div class="input-box">
                        <div class="input-label">
                            <span>身份</span>
                        </div>
                        <div class="input-container">
                                <el-select v-model="selectedUser.role" style="margin-left: 10px;">
                                    <el-option
                                        v-for="item in userRoleList"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    />
                                </el-select>   
                        </div>
                    </div>
                    <div class="input-box">
                        <div class="input-label">
                            <span>状态</span>
                        </div>
                        <div class="input-container">
                            <el-select v-model="selectedUser.status" style="margin-left: 10px;">
                                    <el-option
                                        v-for="item in userStatusList"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    />
                                </el-select>   
                        </div>
                    </div>
                </div>

                <!-- 对话框底部 -->
                <div class="dialog-footer">
                    <el-button class="logout-btn" style="color: #8D8C8C;" @click="closeDialog">
                        <span>取消</span>
                    </el-button>
                    <el-button class="edit-btn" @click="submitDialog">
                        <span>保存</span>
                    </el-button>
                </div>
            </div>
        </div>

</template>

<style scoped>
.bar {
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
  height: 60px;
}
.table-header {
  display: flex;        /* 开启 Flex 布局 */
  align-items: center;  /* 垂直居中） */
  justify-content: center; /* 水平居中 */
  gap: 6px;             /* 图标与文字的间距 */
  height: 100%;         /* 占满表头单元格的高度（66px） */
  font-size: 16px;
}

.status {
  width: 78px;
  height: 26px;
  border-radius: 5px;
  color: #FFFFFF;
  font-size: 13px;
  text-align: center;
  margin: 0 auto;
  padding: 4px 10px;
  line-height: 18px;
}

/* 分页条 */
.pagination {
  position: absolute;
  right: 16px;
  margin-top: 10px;
  bottom: 20px;
}

:deep(.el-table) {
  --el-table-text-color: #2B2B2B;
  --el-table-border: none; 
}
/* 强制设置数据行（tr）的高度为72px */
:deep(.el-table .el-table__row) {
  height: 72px !important; 
}

/* 对话框样式 */
.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}
.dialog-content {
    width: 420px;
    height: 367px;
    background-color: #FFFFFF;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
.dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 70px;
    padding: 0 24px;
    font-size: 18px;
}
.close-btn {
    background-color: transparent;
    border: 0;
    width: 20px;
    height: 20px;
    cursor: pointer;
}
.dialog-body {
    width: 372px;
    height: 200px;
    margin: 0 auto;
    margin-top: 10px;
    /* border: 1px solid red; */
}
.input-box {
    display: flex;
    align-items: center;
    gap: 20px;
    height: 42px;
    margin-bottom: 20px;
}
.input-label {
    width: 60px;
    height: 22px;
    font-size: 16px;
    color: #787980;
}
.input-container {
    display: flex;
    align-items: center;
    height: 100%;
    width: 100%;
    background: #FAFAFA;
    border-radius: 4px;
    border: 1px solid transparent;
}
.input-inner {
    margin-left: 10px;
}
.dialog-footer {
    width: 372px;
    height: 45px;
    margin-top: 10px;
    margin-left: 24px;
}
.dialog-footer .el-button {
    width: 180px;
    height: 100%;
}
.edit-btn {
    background-color: #4077FB;
    color: #fff;
}
.logout-btn {
    background-color: #F2F3F4;
    color: #454545;
}

/* 让下拉框和输入框样式统一：清除默认边框、背景、箭头 */
:deep(.input-container .el-select) {
  /* 覆盖Element UI的默认变量，去掉边框相关样式 */
  --el-select-border-color: transparent;
  --el-select-hover-border-color: transparent;
  --el-select-focus-border-color: transparent;
}

/* 清除下拉框外层容器的样式 */
:deep(.input-container .el-select__wrapper) {
  border: none !important;       /* 去掉边框 */
  box-shadow: none !important;   /* 去掉阴影 */
  background-color: transparent !important; /* 继承content的浅色背景 */
  padding: 0 !important;         /* 去掉默认内边距 */
}

/* 清除输入框（下拉框文本区域）的样式 */
:deep(.input-container .el-select__input) {
  border: none !important;       /* 去掉输入框边框 */
  outline: none !important;      /* 去掉聚焦轮廓 */
  background-color: transparent !important; /* 透明背景 */
  padding: 0 !important;         /* 去掉内边距 */
  margin: 0 !important;          /* 去掉外边距 */
}
/* 解决按钮 hover 变色：覆盖 edit-btn 的 hover 样式 */
:deep(.edit-btn:hover) {
  background-color: #4077FB !important; /* 与默认背景色一致 */
  color: #fff !important;               /* 与默认文字色一致 */
  border: 0 !important;                 /* 保持无边框 */
}

/* 解决按钮 hover 变色：覆盖 logout-btn 的 hover 样式 */
:deep(.logout-btn:hover) {
  background-color: #F2F3F4 !important; /* 与默认背景色一致 */
  color: #454545 !important;            /* 与默认文字色一致 */
  border: 0 !important;                 /* 保持无边框 */
}
:deep(.el-select__placeholder) {
    color: #fff;
    background-color: #4077FB;
    width: 100px;
    border-radius: 5px;
    text-align: center;
    font-weight: 500;
    height: 28px;
    line-height: 28px;
}
</style>